<template>
  <div class="goods-operation">
    <div class="step-list">
      <Row>
        <Col span="24">
          <steps :current="activestep" style="height: 60px; margin-top: 10px">
            <step title="基本信息" />
            <step title="规格参数" />
            <step title="销售属性" />
            <step title="SKU信息" />
            <step title="保存完成" />
          </steps>
        </Col>

        <!-- 第一步 基本信息 -->
        <Col span="24" v-show="activestep == 0">
          <Card style="width: 100%">
            <Form :model="spu" :label-width="80">
              <FormItem label="商品名称:">
                <Input
                  v-model="spu.spuName"
                  placeholder="请输入商品名称"
                ></Input>
              </FormItem>
              <FormItem label="商品描述:">
                <Input
                  v-model="spu.spuDescription"
                  placeholder="请输入商品描述"
                ></Input>
              </FormItem>
              <FormItem label="选择分类:">
                <CateCascader
                  @selected="selectedCate"
                  :cateId="spu.catelogId"
                  style="width: 200px"
                />
              </FormItem>
              <FormItem label="选择品牌:">
                <Select v-model="spu.brandId" style="width: 200px">
                  <Option
                    v-for="item in cateBrandList"
                    :value="item.id"
                    :key="item.name"
                    >{{ item.name }}</Option
                  >
                </Select>
              </FormItem>
              <FormItem label="商品重量:">
                <InputNumber v-model="spu.weight" controls-outside />
              </FormItem>
              <FormItem label="设置积分:">
                金币
                <InputNumber v-model="spu.bounds.buyBounds" controls-outside />
                成长值
                <InputNumber v-model="spu.bounds.growBounds" controls-outside />
              </FormItem>
              <FormItem label="商品图集:">
                <upload-pic-multiple
                  v-model="spu.images"
                  :pictureList="spu.images"
                  @imagesUpload="imagesUploadSuccess"
                  style="width: 80%"
                ></upload-pic-multiple>
              </FormItem>
              <FormItem label="商品描述:">
                <upload-pic-single
                  v-model="spu.decript"
                  :pictureList="spu.decript"
                  @descriptSuccess="descriptUploadSuccess"
                  style="width: 80%"
                ></upload-pic-single>
              </FormItem>
              <FormItem>
                <Button type="primary" @click="nextToAttrInfo"
                  >下一步:设置规格参数</Button
                >
              </FormItem>
            </Form>
          </Card>
        </Col>
        <!-- 第二步 规格参数-->
        <Col span="24" v-show="activestep == 1">
          <Card style="width: 100%">
            <Tabs value="name1" type="card" style="height: 600px">
              <TabPane
                v-for="(group, gid) in dataResp.attrGroups"
                :key="group.attrGroupId"
                :label="group.attrGroupName"
              >
                <Form ref="spu" :model="spu">
                  <FormItem
                    :label="attr.attrName"
                    v-for="(attr, aidx) in group.attrs"
                    :key="attr.attrId"
                  >
                    <Select
                      style="width: 200px"
                      v-model="dataResp.baseAttrs[gid][aidx].attrValues"
                      multiple
                      filterable
                      allow-create
                      @on-create="handleCreate1"
                    >
                      <Option
                        v-for="(val, vidx) in attr.valueSelect.split(';')"
                        :value="val"
                        :key="vidx"
                        >{{ val }}
                      </Option>
                    </Select>
                  </FormItem>
                </Form>
              </TabPane>
            </Tabs>
            <div style="margin: auto">
              <Button
                type="success"
                style="margin-right: 10px"
                @click="activestep = 0"
                >上一步</Button
              >
              <Button type="primary" @click="generateSaleAttrs"
                >下一步:设置销售属性</Button
              >
            </div>
          </Card>
        </Col>
        <!-- 第三步 销售属性 -->
        <Col span="24" v-show="activestep == 2">
          <Card style="width: 100%">
            <span>选择销售属性</span>
            <Form :model="spu">
              <FormItem
                v-for="(attr, aidx) in dataResp.saleAttrs"
                :key="attr.attrId"
                :label="attr.attrName"
              >
                <Input
                  v-model="dataResp.tempSaleAttrs[aidx].attrId"
                  v-show="false"
                  style="width: 300px"
                />
                <CheckboxGroup
                  v-model="dataResp.tempSaleAttrs[aidx].attrValues"
                >
                  <Checkbox
                    v-for="val in dataResp.saleAttrs[aidx].valueSelect.split(
                      ';'
                    )"
                    :key="val"
                    :label="val"
                    v-if="dataResp.saleAttrs[aidx].valueSelect != ''"
                  ></Checkbox>
                  <div style="margin-left: 20px; display: inline">
                    <Button
                      v-show="!inputVisible[aidx].view"
                      @click="showInput(aidx)"
                      >自定义</Button
                    >
                    <Input
                      v-show="inputVisible[aidx].view"
                      v-model="inputValue[aidx].val"
                      style="width: 150px"
                      @keyup.enter.native="handleInputConfirm(aidx)"
                      @blur.native.capture="handleInputConfirm(aidx)"
                    >
                    </Input>
                  </div>
                </CheckboxGroup>
              </FormItem>
            </Form>
            <div style="margin: auto">
              <Button
                type="success"
                style="margin-right: 10px"
                @click="activestep = 1"
                >上一步</Button
              >
              <Button type="primary" @click="generateSkus"
                >下一步:设置SKU信息</Button
              >
            </div>
          </Card>
        </Col>
        <!-- 第四步 SKU信息 -->
        <Col span="24" v-show="activestep == 3">
          <Card style="width: 100%">
            <Table border :columns="columns" :data="spu.skus">
              <template #productName="{ index }">
                <Input v-model="spu.skus[index].skuName" style="width: auto" />
              </template>
              <template #productTitle="{ index }">
                <Input v-model="spu.skus[index].skuTitle" style="width: auto" />
              </template>
              <template #skuSubtitle="{ index }">
                <Input
                  v-model="spu.skus[index].skuSubtitle"
                  style="width: auto"
                />
              </template>
              <template #price="{ index }">
                <Input v-model="spu.skus[index].price" style="width: auto" />
              </template>
              <template #stock="{ index }">
                <Input v-model="spu.skus[index].stock" style="width: auto" />
              </template>
            </Table>
            <div style="margin: auto; margin-top: 10px">
              <Button
                type="success"
                style="margin-right: 10px"
                @click="activestep = 2"
                >上一步</Button
              >
              <Button type="primary" @click="saveProduct"
                >下一步:保存商品信息</Button
              >
            </div>
          </Card>
        </Col>
        <!-- 第五步 保存完成 -->
        <Col span="24" v-show="activestep == 4">
          <Card style="width: 100%">
            <h1 style="align: center">保存完毕,请等待官方审核</h1>
          </Card>
        </Col>
      </Row>
    </div>

    <!-- 第一步 选择分类 -->
    <!-- <first-step ref='first' v-show="activestep === 0" @change="getFirstData"></first-step> -->
    <!-- 第二步 商品详细信息 -->
    <!-- <second-step ref='second' :firstData="firstData" v-if="activestep === 1"></second-step> -->
    <!-- 第三步 发布完成 -->
    <!-- <third-step ref='third' v-if="activestep === 2"></third-step> -->
  </div>
</template>
<script>
import CateCascader from '@/views/my-componts/CateCascader.vue';
import UploadPicMultiple from '@/views/my-componts/UploadPicMultiple.vue';
import UploadPicSingle from '@/views/my-componts/UploadPicSingle.vue';
import * as ApiBrand from '@/api/myapi/Brand';
import * as ApiGroup from '@/api/myapi/Group';
import * as ApiAttr from '@/api/myapi/Attr';
import * as ApiProduct from '@/api/myapi/Product';
export default {
  name: 'addGoods',
  components: {
    CateCascader,
    UploadPicMultiple,
    UploadPicSingle,
  },

  data() {
    return {
      /** 当前激活步骤*/
      activestep: 0,
      // firstData: {}, // 第一步传递的数据
      // spu的信息存储
      spu: {
        //要提交的数据
        spuName: '',
        spuDescription: '',
        catalogId: 0,
        brandId: '',
        weight: 0,
        publishStatus: 0,
        decript: [], //商品详情
        images: [], //商品图集，最后sku也可以新增
        bounds: {
          //积分
          buyBounds: 0,
          growBounds: 0,
        },
        baseAttrs: [], //基本属性
        skus: [], //所有sku信息
      },
      // 表单信息校验
      spuBaseInfoRules: {
        spuName: [
          { required: true, message: '请输入商品名字', trigger: 'blur' },
        ],
        spuDescription: [
          { required: true, message: '请编写一个简单描述', trigger: 'blur' },
        ],
        catalogId: [
          { required: true, message: '请选择一个分类', trigger: 'blur' },
        ],
        brandId: [
          { required: true, message: '请选择一个品牌', trigger: 'blur' },
        ],
        decript: [
          { required: true, message: '请上传商品详情图集', trigger: 'blur' },
        ],
        images: [
          { required: true, message: '请上传商品图片集', trigger: 'blur' },
        ],
        weight: [
          {
            type: 'number',
            required: true,
            message: '请填写正确的重量值',
            trigger: 'blur',
          },
        ],
      },
      // 当前cateId对应的品牌信息
      cateBrandList: [],
      dataResp: {
        //后台返回的所有数据
        attrGroups: [],
        baseAttrs: [],
        saleAttrs: [],
        tempSaleAttrs: [],
        tableAttrColumn: [],
        memberLevels: [],
        steped: [false, false, false, false, false],
      },
      inputVisible: [],
      inputValue: [],
      tableGroupData: [],
      // table的列
      columns: [],
      skuImageList: [], //存储sku的图片集
      skuIntroImage: [], // sku的详细信息图
      loading: true,
    };
  },
  methods: {
    // 组件CateCascader的回调
    selectedCate(item) {
      let arr = item[0];
      this.spu.catalogId = arr[2];
      this.searchBrand(arr[2]);
    },
    searchBrand(cateId) {
      ApiBrand.getCateBrandRelation(cateId).then((res) => {
        if (res.data.code == 201) {
          this.cateBrandList = res.data.obj;
        }
      });
    },
    nextToAttrInfo() {
      this.activestep = 1;
      this.getBaseAttr();
    },
    // 商品图片集上传成功
    imagesUploadSuccess(param) {
      this.spu.images = param;
    },
    // 商品详情描述上传成
    descriptUploadSuccess(param) {
      this.spu.decript = param;
    },
    // 获取规格参数
    getBaseAttr() {
      ApiGroup.getGroupAndGroupOwnerAttr(this.spu.catalogId).then((res) => {
        if (res.data.code == 201) {
          let data = res.data.obj;
          data.forEach((item) => {
            let attrArry = [];
            if (item.attrs) {
              item.attrs.forEach((attr) => {
                attrArry.push({
                  attrId: attr.attrId,
                  attrName: attr.attrName,
                  // attrValues: "",
                  attrValues: attr.valueSelect,
                  showDesc: attr.showDesc,
                });
              });
            }

            this.dataResp.baseAttrs.push(attrArry);
          });

          this.dataResp.steped[0] = 0;
          this.dataResp.attrGroups = res.data.obj;
        }
      });
    },
    handleCreate1(val) {
      // console.log('handleCreate1的Val:', val);
    },
    // 设置销售属性
    generateSaleAttrs() {
      this.spu.baseAttrs = [];

      this.dataResp.baseAttrs.forEach((item) => {
        item.forEach((attr) => {
          let { attrId, attrName, attrValues, showDesc } = attr;
          if (attrValues != '') {
            if (attrValues instanceof Array) {
              //多个值用;隔开
              attrValues = attrValues.join(';');
            }
            this.spu.baseAttrs.push({ attrId, attrName, attrValues, showDesc });
          }
        });
      });
      // console.log('测试baseAttrs：', this.spu.baseAttrs);
      this.activestep = 2; //跳转到下一步
      this.getSaleAttr();
    },
    // 获取销售属性
    getSaleAttr() {
      ApiAttr.getSaleAttrs(this.spu.catalogId).then((res) => {
        if (res.data.code == 201) {
          this.dataResp.saleAttrs = res.data.obj;
          let data = res.data.obj;
          data.forEach((item) => {
            this.dataResp.tempSaleAttrs.push({
              attrId: item.attrId,
              attrValues: [],
              attrName: item.attrName,
            });
            this.inputVisible.push({ view: false });
            this.inputValue.push({ val: '' });
          });
        }
      });
    },
    showInput(aidx) {
      this.inputVisible[aidx].view = true;
    },
    handleInputConfirm(idx) {
      let inputValue = this.inputValue[idx].val;
      if (inputValue) {
        // this.dynamicTags.push(inputValue);
        if (this.dataResp.saleAttrs[idx].valueSelect == '') {
          this.dataResp.saleAttrs[idx].valueSelect = inputValue;
        } else {
          this.dataResp.saleAttrs[idx].valueSelect += ';' + inputValue;
        }
      }
      // console.log('测试handleInputConfirm:', this.inputValue);
      // console.log('测试handleInputConfirm:', this.dataResp.saleAttrs);
      this.inputVisible[idx].view = false;
      this.inputValue[idx].val = '';
    },
    // 设置SKU信息
    generateSkus() {
      // console.log('测试设置sku信息:', this.spu);

      //根据笛卡尔积运算进行生成sku
      let selectValues = [];
      this.dataResp.tableAttrColumn = [];
      this.dataResp.tempSaleAttrs.forEach((item) => {
        if (item.attrValues.length > 0) {
          selectValues.push(item.attrValues);
          this.dataResp.tableAttrColumn.push(item);
        }
      });
      // 进行计算
      let descartes = this.Mydescartes(selectValues);
      // console.log("生成的组合", JSON.stringify(descartes));

      let skus = [];

      descartes.forEach((descar, descaridx) => {
        let attrArray = []; //sku属性组
        descar.forEach((de, index) => {
          //构造saleAttr信息
          let saleAttrItem = {
            attrId: this.dataResp.tableAttrColumn[index].attrId,
            attrName: this.dataResp.tableAttrColumn[index].attrName,
            attrValue: de,
          };
          attrArray.push(saleAttrItem);
        });
        //先初始化几个images，后面的上传还要加
        let imgs = [];
        imgs.push({ imgUrl: this.spu.images, defaultImg: 0 });

        //会员价，也必须在循环里面生成，否则会导致数据绑定问题
        let memberPrices = [];
        if (this.dataResp.memberLevels.length > 0) {
          for (let i = 0; i < this.dataResp.memberLevels.length; i++) {
            if (this.dataResp.memberLevels[i].priviledgeMemberPrice == 1) {
              memberPrices.push({
                id: this.dataResp.memberLevels[i].id,
                name: this.dataResp.memberLevels[i].name,
                price: 0,
              });
            }
          }
        }
        //;descaridx，判断如果之前有就用之前的值;
        let res = this.hasAndReturnSku(this.spu.skus, descar);
        if (res === null) {
          skus.push({
            attr: attrArray,
            skuName: this.spu.spuName + ' ' + descar.join(' '),
            price: 0,
            skuTitle: this.spu.spuName + ' ' + descar.join(' '),
            skuSubtitle: '',
            images: imgs,
            descar: descar,
            fullCount: 0,
            discount: 0,
            countStatus: 0,
            fullPrice: 0.0,
            reducePrice: 0.0,
            priceStatus: 0,
            memberPrice: new Array().concat(memberPrices),
            skuImages: [],
            skuIntroImage: [],
            stock: 0,
          });
        } else {
          skus.push(res);
        }
      });
      this.spu.skus = skus;
      this.spu.skus.tableData = []; // 用来组合列
      this.dataResp.tableAttrColumn.forEach((item, index) => {
        let data = {
          title: item.attrName,
          key: 'attr',
          align: 'center',
          width: 200,
          render: (h, params) => {
            return h('div', {}, params.row.attr[index].attrValue);
          },
        };
        this.spu.skus.tableData.push(data);
      });
      // console.log("结果!!!", this.spu.skus, this.dataResp.tableAttrColumn);
      this.columns = this.countColumns();
      // console.log('测试countColumns:', this.columns);
      // 初始化sku图片保存集
      this.spu.skus.forEach((item, index) => {
        let temp = { index: index, value: [] };
        let temp2 = { index: index, value: [] };
        this.skuImageList.push(temp);
        this.skuIntroImage.push(temp2);
      });
      // console.log('测试skuImageList',this.skuImageList);
      // console.log('测试skuIntroImage',this.skuIntroImage);
      this.activestep = 3;
    },
    //笛卡尔积运算
    Mydescartes(list) {
      // console.log('测试Mydescartes:', list);
      if (list.length < 2) {
        return [];
      }

      return list.reduce((total, currentValue) => {
        let res = [];

        total.forEach((t) => {
          currentValue.forEach((cv) => {
            if (t instanceof Array)
              // 或者使用 Array.isArray(t)
              res.push([...t, cv]);
            else res.push([t, cv]);
          });
        });
        return res;
      });
    },
    //判断如果包含之前的sku的descar组合，就返回这个sku的详细信息；
    hasAndReturnSku(skus, descar) {
      let res = null;
      if (skus.length > 0) {
        for (let i = 0; i < skus.length; i++) {
          if (skus[i].descar.join(' ') == descar.join(' ')) {
            res = skus[i];
          }
        }
      }
      return res;
    },
    // 计算表格列
    countColumns() {
      let result = []; // 要返回的是一个数组
      let tableCombo = {
        title: '属性组合',
        align: 'center',
        children: this.spu.skus.tableData,
      };
      result.push(tableCombo);

      let productName = {
        title: '商品名称',
        slot: 'productName',
        align: 'center',
      };
      result.push(productName);

      let productTitle = {
        title: '标题',
        slot: 'productTitle',
        align: 'center',
      };
      result.push(productTitle);

      let productSubTitle = {
        title: '副标题',
        slot: 'skuSubtitle',
        align: 'center',
      };
      result.push(productSubTitle);

      let productPrice = {
        title: '价格',
        slot: 'price',
        align: 'center',
      };
      result.push(productPrice);

      let stock = {
        title: '库存',
        slot: 'stock',
        align: 'center',
      };
      result.push(stock);

      let expandColumns = {
        type: 'expand',
        width: 50,
        render: (h, params) => {
          let _this = this; // 因为render的return中不可以直接调用this,所以这里先复制
          return h('div', [
            h(
              'label',
              {
                style: {
                  display: 'block',
                  float: 'left',
                  'margin-right': '10px',
                },
              },
              '设置图集'
            ),
            h(
              UploadPicMultiple,
              {
                on: {
                  // 处理上传组件的事件imagesUpload
                  imagesUpload: (value) => {
                    //上传成功  把图片传进数组里面
                    this.addSkuImages(value, params.index);
                    // console.log('上传图片后的skuImageList:', this.skuImageList);
                  },
                },
              },
              ''
            ),
            h('br', {}, ''),
            h(
              'label',
              {
                style: {
                  display: 'block',
                  float: 'left',
                  'margin-right': '10px',
                },
              },
              '设置商品介绍图'
            ),
            h(
              UploadPicSingle,
              {
                on: {
                  // 处理上传组件的事件imagesUpload
                  descriptSuccess: (value) => {
                    //上传成功  把图片传进数组里面
                    this.addSkuIntroImage(value, params.index);
                    // console.log('上传图片后的skuIntroImage:', this.skuIntroImage);
                  },
                },
              },
              ''
            ),
          ]);
        },
      };

      result.push(expandColumns);

      return result;
    },
    addSkuImages(value, index) {
      // console.log('测试value:', value);
      let images = {
        imgUrl: '',
        defaultImg: 0,
      };
      images.imgUrl = value;
      this.skuImageList[index].value.push(images);
    },
    addSkuIntroImage(value, index) {
      // console.log('测试value:', value);
      let images = {
        imgUrl: '',
        defaultImg: 0,
      };
      images.imgUrl = value;
      this.skuIntroImage[index].value.push(images);
    },
    // 保存商品
    saveProduct() {
      // 把skuImageList和skuIntroImage的图片先赋值给this.spu
      this.spu.skus.forEach((item, index) => {
        item.skuImages = this.skuImageList[index].value;
        item.skuIntroImage = this.skuIntroImage[index].value;
      });
      let storeInfo = JSON.parse(localStorage.getItem('storeInfo'));

      this.spu.storeId = storeInfo.id;
      this.spu.storeName = storeInfo.storeName;
      // console.log('点击上传商品:', this.spu);

      this.$Modal.confirm({
        title: '确认审核',
        content: '将要提交商品数据,需要一小段时间,是否继续?',
        // loading: this.loading,
        onOk: () => {
          ApiProduct.saveSpu(this.spu).then((res) => {
            if (res.data.code == 201) {
              // this.loading = false
              this.activestep = 4;
            } else {
              this.$Message.error('网络延迟,请稍后重试');
            }
          });
        },
      });
    },
  },
  mounted() {
    // 编辑商品、模板
    // if (this.$route.query.id || this.$route.query.draftId) {
    //   this.activestep = 1;
    // } else {
    //   this.activestep = 0
    //   this.$refs.first.selectGoodsType = true;
    // }
  },
};
</script>
<style lang="scss" scoped>
@import './addGoods.scss';
</style>
